package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.ElderFamilyDto;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.zzyl.nursing.service.*;
import com.zzyl.nursing.utils.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * 入住Service业务层处理
 *
 * @author alexis
 * @date 2025-06-07
 */
@Service
@Slf4j
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private IElderService elderService;
    @Autowired
    private IBedService bedService;
    @Autowired
    private IContractService contractService;
    @Autowired
    private ICheckInConfigService checkInConfigService;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return checkInMapper.deleteById(id);
    }

    /**
     * 入住申请
     *
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void checkInApply(CheckInApplyDto dto) {
        //1.判断老人是否已经入住
        Elder elder = elderService.lambdaQuery().eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo()).one();
        if (elder != null && elder.getStatus() == 1) {
            //抛出异常,老人已经存在
            throw new RuntimeException("老人已入住");
        }
        //2.更新床位信息
        //update bed set status=1 where bed_id=?
        bedService.lambdaUpdate().set(Bed::getBedStatus, 1).eq(Bed::getId, dto.getCheckInConfigDto().getBedId()).update();
        //3.如果没有查询到老人信息，那就新增老人，如果查询到老人信息，说明他之前住过，就有id了,那就更新他的信息
        //根据bed_id查询bed_number
        Bed bed = bedService.lambdaQuery().eq(Bed::getId, dto.getCheckInConfigDto().getBedId()).one();
        if (bed == null) {
            throw new RuntimeException("没有改床位");
        }
        Elder newElder = BeanUtil.toBean(dto.getCheckInElderDto(), Elder.class);
        newElder.setStatus(1);
        newElder.setBedNumber(bed.getBedNumber());
        newElder.setBedId(bed.getId());
        if (elder != null) {
            newElder.setId(elder.getId());
        }
        elderService.saveOrUpdate(newElder);
        //4.新增入住合同
        Contract contract = BeanUtil.toBean(dto.getCheckInContractDto(), Contract.class);
        contract.setElderId(newElder.getId());
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());
        contract.setElderName(newElder.getName());
        contract.setStartDate(dto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(dto.getCheckInConfigDto().getEndDate());
        //判断合同是否生效，开始日期>now,未生效
        boolean date = dto.getCheckInConfigDto().getStartDate().isBefore(LocalDateTime.now());
        contract.setStatus(date ? 1 : 0);
        contractService.save(contract);
        //5.新增入住信息
        CheckIn checkIn = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckIn.class);
        checkIn.setElderName(newElder.getName());
        checkIn.setElderId(newElder.getId());
        checkIn.setIdCardNo(newElder.getIdCardNo());
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setStatus(0);//默认都给他设置已经入住，后边通过定时任务来进行修改完成
        List<ElderFamilyDto> elderFamilyDtoList = dto.getElderFamilyDtoList();
        //将其转换为json字符串
        checkIn.setRemark(JSONUtil.toJsonStr(elderFamilyDtoList));
        this.save(checkIn);
        //6.新增入住配置
        CheckInConfig checkInConfig = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckInConfig.class);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigService.save(checkInConfig);
    }

    /**
     * 查询入住详情
     *
     * @param id 入住id
     * @return
     */
    @Override
    public CheckInDetailVo getCheckInDetailById(Long id) {
        CheckInDetailVo vo = new CheckInDetailVo();
        //查询入住信息
        CheckIn checkIn = this.getById(id);
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        Elder elder = elderService.lambdaQuery().eq(Elder::getId, checkIn.getElderId()).one();
        BeanUtil.copyProperties(elder, checkInElderVo);
        String[] split = elder.getBirthday().split("-");
        Integer newAge = Integer.parseInt(split[0]);
        Integer now = Integer.parseInt(LocalDateTime.now().toString().split("-")[0]);
        checkInElderVo.setAge(now - newAge);
        vo.setCheckInElderVo(checkInElderVo);

        //根据eld_id查询合同
        Contract contract = contractService.lambdaQuery().eq(Contract::getElderId, checkIn.getElderId()).one();
        vo.setContract(contract);

        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        CheckInConfig checkInConfig = checkInConfigService.lambdaQuery().eq(CheckInConfig::getCheckInId, checkIn.getId()).one();
        BeanUtil.copyProperties(checkInConfig, checkInConfigVo, true);
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());

        log.info("checkInConfigVo:{}", checkInConfigVo);
        vo.setCheckInConfigVo(checkInConfigVo);

        List<ElderFamilyVo> list = JSONUtil.toList(checkIn.getRemark(), ElderFamilyVo.class);
        vo.setElderFamilyVoList(list);
        return vo;
    }
}
